import React from "react";
import { Plus } from "lucide-react";
import { cn } from "../lib/utils";

const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

const ImageUploader = ({ onChange, value }) => {
  const ref = React.useRef(null);

  const handleImageUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) {
      return;
    }

    ref.current.value = null; // Clear the input value

    const res = await fileToBase64(file);
    onChange(res);
  };

  let children = <Plus size={64} />;
  if (value) {
    children = (
      <img src={value} className="w-full h-full object-contain rounded-lg" />
    );
  }

  return (
    <div>
      <div
        className={cn(
          "w-32 cursor-pointer h-32 flex justify-center items-center",
          !value && "border border-dashed text-4xl",
          value && "bg-black/60"
        )}
        onClick={() => {
          ref.current.click();
        }}
      >
        {children}
      </div>
      <input
        ref={ref}
        type="file"
        className="hidden"
        accept="image/*"
        onChange={handleImageUpload}
      />
    </div>
  );
};

export default ImageUploader;
